import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../config/app_config.dart';
import '../config/local_config_manager.dart';
import '../services/providers/auth_provider.dart';

class ConfigPage extends ConsumerStatefulWidget {
  const ConfigPage({super.key});

  @override
  ConsumerState<ConfigPage> createState() => _ConfigPageState();
}

class _ConfigPageState extends ConsumerState<ConfigPage> {
  final _formKey = GlobalKey<FormState>();
  
  // 核心配置控制器
  late TextEditingController _baseUrlController;
  late TextEditingController _tcpHostController;
  late TextEditingController _tcpPortController;
  
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    // 延迟初始化，避免在widget构建期间修改provider
    Future(() => _initializeControllersAsync());
  }

  void _initializeControllersAsync() async {
    // 强制重新加载配置以确保获取最新值
    await LocalConfigManager.instance.forceReload();
    
    final config = AppConfig.instance;
    _baseUrlController = TextEditingController(text: config.baseUrl);
    _tcpHostController = TextEditingController(text: config.tcpTunnelHost);
    _tcpPortController = TextEditingController(text: config.tcpTunnelPort.toString());
    
    debugPrint('🔄 ConfigPage: 控制器已初始化');
    debugPrint('   baseUrl: ${config.baseUrl}');
    debugPrint('   tcpHost: ${config.tcpTunnelHost}');
    debugPrint('   tcpPort: ${config.tcpTunnelPort}');
    
    // 通知UI更新
    if (mounted) {
      setState(() {});
    }
  }

  /// 刷新控制器内容（不重新创建控制器）
  Future<void> _refreshControllers() async {
    // 强制重新加载配置以确保获取最新值
    await LocalConfigManager.instance.forceReload();
    
    final config = AppConfig.instance;
    
    // 更新控制器的文本内容，而不是重新创建控制器
    _baseUrlController.text = config.baseUrl;
    _tcpHostController.text = config.tcpTunnelHost;
    _tcpPortController.text = config.tcpTunnelPort.toString();
    
    debugPrint('🔄 ConfigPage: 控制器内容已刷新');
    debugPrint('   baseUrl: ${config.baseUrl}');
    debugPrint('   tcpHost: ${config.tcpTunnelHost}');
    debugPrint('   tcpPort: ${config.tcpTunnelPort}');
  }

  @override
  void dispose() {
    _baseUrlController.dispose();
    _tcpHostController.dispose();
    _tcpPortController.dispose();
    super.dispose();
  }

  Future<void> _saveConfig() async {
    if (_formKey.currentState == null || !_formKey.currentState!.validate()) return;

    // 显示确认对话框，告知用户保存配置会导致重新登录
    final confirmed = await _showSaveConfirmDialog();
    if (!confirmed) return;

    setState(() {
      _isLoading = true;
    });

    try {
      debugPrint('🔄 ConfigPage: 开始保存配置到本地存储');

      // 直接保存到本地配置管理器
      final success = await AppConfig.instance.updateConfig(
        baseUrl: _baseUrlController.text.trim(),
        tcpHost: _tcpHostController.text.trim(),
        tcpPort: int.parse(_tcpPortController.text),
      );

      if (!success) {
        throw Exception('配置保存失败');
      }

      debugPrint('✅ ConfigPage: 配置保存成功');

      // 刷新当前页面的配置显示（不重新创建控制器）
      await _refreshControllers();
      setState(() {});

      if (mounted) {
        // 显示保存成功消息
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.check_circle, color: Colors.white),
                const SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      const SelectableText('配置保存成功', style: TextStyle(fontWeight: FontWeight.bold)),
                      SelectableText('已更新: ${_baseUrlController.text}', style: const TextStyle(fontSize: 12)),
                      const SelectableText('正在退出登录...', style: TextStyle(fontSize: 11, color: Colors.white70)),
                    ],
                  ),
                ),
              ],
            ),
            backgroundColor: Colors.green,
            duration: const Duration(seconds: 2),
          ),
        );
        
        // 延迟一下让用户看到保存成功的消息
        await Future.delayed(const Duration(milliseconds: 1500));
        
        if (mounted) {
          // 执行退出登录操作
          await _logoutAndRedirectToLogin();
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: SelectableText('❌ 配置保存失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _resetToDefault() async {
    try {
      // 重置配置为默认值
      await AppConfig.instance.resetToDefault();
      
      // 更新控制器内容而不是重新创建
      await _refreshControllers();
      setState(() {});
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: SelectableText('配置已重置为默认值')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: SelectableText('重置配置失败: $e')),
        );
      }
    }
  }

  void _copyConfigInfo() {
    final configText = AppConfig.instance.getDebugInfo();
    
    Clipboard.setData(ClipboardData(text: configText));
    
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: SelectableText('配置信息已复制到剪贴板')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('配置管理'),
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: _copyConfigInfo,
            tooltip: '复制配置信息',
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            Card(
              elevation: 4,
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.settings, color: Theme.of(context).primaryColor),
                        const SizedBox(width: 8),
                        SelectableText(
                          '核心配置管理',
                          style: Theme.of(context).textTheme.titleLarge?.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                    
                    // API基础URL配置
                    TextFormField(
                      controller: _baseUrlController,
                      decoration: const InputDecoration(
                        labelText: 'API 基础URL',
                        hintText: 'http://127.0.0.1:8080',
                        prefixIcon: Icon(Icons.link),
                        border: OutlineInputBorder(),
                        helperText: '服务器API接口地址',
                      ),
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return '请输入API基础URL';
                        }
                        final uri = Uri.tryParse(value.trim());
                        if (uri == null || !uri.hasScheme) {
                          return '请输入有效的URL (如: http://ip:port)';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 20),
                    
                    // TCP隧道主机配置
                    TextFormField(
                      controller: _tcpHostController,
                      decoration: const InputDecoration(
                        labelText: 'TCP隧道主机',
                        hintText: '127.0.0.1',
                        prefixIcon: Icon(Icons.computer),
                        border: OutlineInputBorder(),
                        helperText: '隧道服务器IP地址或域名',
                      ),
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return '请输入TCP隧道主机地址';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 20),
                    
                    // TCP隧道端口配置
                    TextFormField(
                      controller: _tcpPortController,
                      decoration: const InputDecoration(
                        labelText: 'TCP隧道端口',
                        hintText: '9001',
                        prefixIcon: Icon(Icons.sync_alt),
                        border: OutlineInputBorder(),
                        helperText: '隧道服务器监听端口',
                      ),
                      keyboardType: TextInputType.number,
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return '请输入TCP隧道端口';
                        }
                        final port = int.tryParse(value.trim());
                        if (port == null || port <= 0 || port > 65535) {
                          return '请输入有效的端口号(1-65535)';
                        }
                        return null;
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24),
            Row(
              children: [
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: _isLoading ? null : _resetToDefault,
                    icon: const Icon(Icons.refresh),
                    label: const SelectableText('重置默认'),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  flex: 2,
                  child: ElevatedButton.icon(
                    onPressed: _isLoading ? null : _saveConfig,
                    icon: _isLoading 
                        ? const SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                          )
                        : const Icon(Icons.save),
                    label: SelectableText(_isLoading ? '保存中...' : '保存配置'),
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      backgroundColor: Theme.of(context).primaryColor,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 20),
            Card(
              elevation: 2,
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.info_outline, size: 20, color: Theme.of(context).primaryColor),
                        const SizedBox(width: 8),
                        SelectableText(
                          '当前配置',
                          style: Theme.of(context).textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    _buildConfigItem('API地址', AppConfig.instance.baseUrl),
                    _buildConfigItem('TCP主机', AppConfig.instance.tcpTunnelHost),
                    _buildConfigItem('TCP端口', AppConfig.instance.tcpTunnelPort.toString()),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 移除了onConfigurationChanged方法，因为我们现在使用Provider系统来监听配置变化

  /// 退出登录并重定向到登录页面
  Future<void> _logoutAndRedirectToLogin() async {
    try {
      debugPrint('🔄 ConfigPage: 开始执行退出登录');
      
      // 获取AuthNotifier并执行退出登录
      final authNotifier = ref.read(authProvider.notifier);
      await authNotifier.logout();
      
      debugPrint('✅ ConfigPage: 退出登录成功');
      
      if (mounted) {
        // 显示退出登录成功的提示
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Row(
              children: [
                Icon(Icons.logout, color: Colors.white),
                SizedBox(width: 8),
                SelectableText('已退出登录，请重新登录'),
              ],
            ),
            backgroundColor: Colors.blue,
            duration: Duration(seconds: 2),
          ),
        );
        
        // 导航到登录页面，清除所有路由历史
        Navigator.of(context).pushNamedAndRemoveUntil(
          '/login', 
          (route) => false, // 清除所有路由历史
        );
      }
    } catch (e) {
      debugPrint('❌ ConfigPage: 退出登录失败: $e');
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.error, color: Colors.white),
                const SizedBox(width: 8),
                Expanded(child: SelectableText('退出登录失败: $e')),
              ],
            ),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
        
        // 即使退出失败，也尝试导航到登录页面
        Navigator.of(context).pushNamedAndRemoveUntil(
          '/login', 
          (route) => false,
        );
      }
    }
  }

  /// 显示保存配置确认对话框
  Future<bool> _showSaveConfirmDialog() async {
    return await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Row(
            children: [
              Icon(Icons.warning_amber_rounded, color: Colors.orange),
              const SizedBox(width: 8),
              const SelectableText('确认保存配置'),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SelectableText('保存配置后将会：'),
              const SizedBox(height: 12),
              _buildConfirmItem('🔄', '应用新的服务器地址'),
              _buildConfirmItem('🚪', '自动退出当前登录'),
              _buildConfirmItem('🔑', '跳转到登录页面重新登录'),
              const SizedBox(height: 12),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.blue.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.blue.withValues(alpha: 0.3)),
                ),
                child: Row(
                  children: [
                    Icon(Icons.info_outline, color: Colors.blue, size: 20),
                    const SizedBox(width: 8),
                    Expanded(
                      child: SelectableText(
                        '这样可以确保新配置立即生效',
                        style: TextStyle(
                          color: Colors.blue.shade700,
                          fontSize: 13,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const SelectableText('取消'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.of(context).pop(true),
              style: ElevatedButton.styleFrom(
                backgroundColor: Theme.of(context).primaryColor,
                foregroundColor: Colors.white,
              ),
              child: const SelectableText('确认保存'),
            ),
          ],
        );
      },
    ) ?? false;
  }

  /// 构建确认项目
  Widget _buildConfirmItem(String emoji, String text) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          SelectableText(emoji, style: const TextStyle(fontSize: 16)),
          const SizedBox(width: 8),
          Expanded(
            child: SelectableText(
              text,
              style: const TextStyle(fontSize: 14),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建配置项显示组件
  Widget _buildConfigItem(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: SelectableText(
              '$label:',
              style: const TextStyle(
                fontWeight: FontWeight.w500,
                color: Colors.grey,
              ),
            ),
          ),
          Expanded(
            child: SelectableText(
              value.isNotEmpty ? value : '未设置',
              style: TextStyle(
                fontFamily: 'monospace',
                color: value.isNotEmpty ? null : Colors.grey,
                fontStyle: value.isNotEmpty ? FontStyle.normal : FontStyle.italic,
              ),
            ),
          ),
        ],
      ),
    );
  }
}